<template>
  <BaseModal 
    v-model="visible" 
    title="注册"
    size="small"
    @close="handleClose"
  >
    <!-- Logo区域 -->
    <div class="logo-section">
      <div class="logo-circle">
        <div class="logo-inner">
          <el-icon size="28"><UserFilled /></el-icon>
        </div>
      </div>
      <h3 class="modal-subtitle">创建新账户，开始您的学习之旅</h3>
    </div>
    
    <!-- 注册表单 -->
    <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="apple-form">
      <div class="form-group">
        <label class="form-label">用户名</label>
        <div class="input-wrapper">
          <el-form-item prop="username">
            <el-input 
              v-model="registerForm.username" 
              placeholder="请输入用户名"
              size="large"
              class="apple-input"
              clearable
            >
              <template #prefix>
                <el-icon class="input-icon"><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">密码</label>
        <div class="input-wrapper">
          <el-form-item prop="password">
            <el-input 
              type="password" 
              v-model="registerForm.password" 
              placeholder="请输入密码"
              size="large"
              class="apple-input"
              show-password
              clearable
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">确认密码</label>
        <div class="input-wrapper">
          <el-form-item prop="confirmPassword">
            <el-input 
              type="password" 
              v-model="registerForm.confirmPassword" 
              placeholder="请再次输入密码"
              size="large"
              class="apple-input"
              show-password
              clearable
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">手机号</label>
        <div class="input-wrapper">
          <el-form-item prop="phone">
            <el-input 
              v-model="registerForm.phone" 
              placeholder="请输入手机号"
              size="large"
              class="apple-input"
              clearable
            >
              <template #prefix>
                <el-icon class="input-icon"><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">邮箱</label>
        <div class="input-wrapper">
          <el-form-item prop="email">
            <el-input 
              v-model="registerForm.email" 
              placeholder="请输入邮箱"
              size="large"
              class="apple-input"
              clearable
            >
              <template #prefix>
                <el-icon class="input-icon"><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">用户类型</label>
        <div class="input-wrapper">
          <el-input 
            value="普通用户" 
            size="large"
            class="apple-input"
            disabled
          >
            <template #prefix>
              <el-icon class="input-icon"><User /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      
      <div class="form-actions">
        <el-button 
          type="primary" 
          @click="submitForm" 
          size="large" 
          class="apple-button"
          :loading="loading"
        >
          <span v-if="!loading">注册</span>
          <span v-else>注册中...</span>
        </el-button>
      </div>
    </el-form>
    
    <!-- 底部链接 -->
    <template #footer>
      <div class="auth-links">
        <el-button type="text" @click="goToLogin" class="apple-link">
          已有账号？立即登录
        </el-button>
      </div>
    </template>
  </BaseModal>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { User, Lock, UserFilled, Phone, Message } from '@element-plus/icons-vue';
import { register as registerApi } from '../../api/auth';
import { useUserStore } from '../../stores/user';
import BaseModal from '../Modals/BaseModal.vue';

interface Props {
  modelValue: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  'close': [];
  'switch-to-login': [];
}>();

const router = useRouter();
const registerFormRef = ref<FormInstance>()
const userStore = useUserStore()
const loading = ref(false);

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  userType: '0',
  phone: '',
  email: '',
});

// 自定义验证规则：确认密码必须与密码一致
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

// 自定义验证规则：检查用户名是否已存在
const validateUsername = async (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名'));
    return;
  }
  
  if (value.length < 3 || value.length > 15) {
    callback(new Error('长度在 3 到 15 个字符'));
    return;
  }
  
  // 只检查用户名长度，不检查是否已存在，让服务器端来处理
  callback();
};

const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
    { validator: validateUsername, trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: ['blur', 'change'] },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
  ],
});

// 监听密码变化，如果确认密码已填写，则重新验证确认密码
watch(
  () => registerForm.password,
  () => {
    if (registerForm.confirmPassword && registerFormRef.value) {
      registerFormRef.value.validateField('confirmPassword');
    }
  }
);

const submitForm = () => {
  if (!registerFormRef.value) return;
  
  registerFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      registerApi({
        username: registerForm.username,
        password: registerForm.password,
        userType: parseInt(registerForm.userType),
        phone: registerForm.phone,
        email: registerForm.email,
      }).then(response => {
        ElMessage.success('注册成功！');
        
        // 注册成功后关闭模态框
        handleClose();
        
        // 注册成功后跳转到登录页面
        setTimeout(() => {
          emit('switch-to-login');
        }, 500);
      }).catch(error => {
        console.error('注册请求失败:', error);
        // 错误消息已经在响应拦截器中显示，这里不再重复显示
        // 只记录错误日志，不显示额外的错误消息
      }).finally(() => {
        loading.value = false;
      });
    } else {
      // 表单验证失败，滚动到第一个错误字段
      if (registerFormRef.value) {
        registerFormRef.value.scrollToField('username');
      }
      return;
    }
  });
};

const handleClose = () => {
  // 重置表单
  registerForm.username = '';
  registerForm.password = '';
  registerForm.confirmPassword = '';
  registerForm.userType = '0';
  registerForm.phone = '';
  registerForm.email = '';
  
  emit('update:modelValue', false);
  emit('close');
};

const goToLogin = () => {
  handleClose();
  emit('switch-to-login');
};
</script>

<style scoped>
/* Logo区域 */
.logo-section {
  text-align: center;
  margin-bottom: 24px;
}

.logo-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  box-shadow: 0 6px 16px rgba(54, 209, 220, 0.3);
  transition: all 0.3s ease;
}

.logo-circle:hover {
  transform: scale(1.05);
  box-shadow: 0 8px 20px rgba(54, 209, 220, 0.4);
}

.logo-inner {
  width: 52px;
  height: 52px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #36d1dc;
}

.modal-subtitle {
  font-size: 16px;
  color: #86868b;
  margin: 0;
  font-weight: 400;
}

/* 表单样式 */
.apple-form {
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 8px;
}

.input-wrapper {
  position: relative;
}

/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 0;
  width: 100%;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
  font-size: 12px;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1;
}

/* 苹果风格输入框 */
.apple-input {
  width: 100%;
}

:deep(.apple-input .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 12px 16px;
  transition: all 0.2s ease;
}

:deep(.apple-input .el-input__wrapper:hover) {
  border-color: rgba(54, 209, 220, 0.4);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

:deep(.apple-input.is-focus .el-input__wrapper) {
  border-color: #36d1dc;
  box-shadow: 0 0 0 3px rgba(54, 209, 220, 0.1);
}

:deep(.apple-input .el-input__inner) {
  font-size: 16px;
  color: #1d1d1f;
  font-weight: 400;
}

:deep(.apple-input .el-input__inner::placeholder) {
  color: #86868b;
}

/* 苹果风格选择框 */
.apple-select {
  width: 100%;
}

:deep(.apple-select .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 12px 16px;
  transition: all 0.2s ease;
}

:deep(.apple-select .el-input__wrapper:hover) {
  border-color: rgba(54, 209, 220, 0.4);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

:deep(.apple-select.is-focus .el-input__wrapper) {
  border-color: #36d1dc;
  box-shadow: 0 0 0 3px rgba(54, 209, 220, 0.1);
}

:deep(.apple-select .el-input__inner) {
  font-size: 16px;
  color: #1d1d1f;
  font-weight: 400;
}

.input-icon {
  color: #86868b;
  font-size: 18px;
}

/* 验证状态图标 */
.valid-icon {
  color: #67c23a;
  font-size: 18px;
}

.invalid-icon {
  color: #f56c6c;
  font-size: 18px;
}

/* 验证状态样式 */
:deep(.is-valid .el-input__wrapper) {
  border-color: #67c23a;
}

:deep(.is-invalid .el-input__wrapper) {
  border-color: #f56c6c;
}

/* 表单操作区域 */
.form-actions {
  margin-top: 24px;
}

/* 苹果风格按钮 */
.apple-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);
  border: none;
  font-size: 16px;
  font-weight: 600;
  color: white;
  box-shadow: 0 4px 14px rgba(54, 209, 220, 0.3);
  transition: all 0.3s ease;
}

:deep(.apple-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(54, 209, 220, 0.4);
}

:deep(.apple-button:active) {
  transform: translateY(0);
  box-shadow: 0 2px 10px rgba(54, 209, 220, 0.3);
}

/* 底部链接 */
.auth-links {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.apple-link {
  font-size: 14px;
  color: #36d1dc;
  font-weight: 500;
  padding: 0;
  transition: all 0.2s ease;
}

:deep(.apple-link:hover) {
  color: #2bb8c3;
  transform: translateY(-1px);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .logo-circle {
    width: 50px;
    height: 50px;
  }
  
  .logo-inner {
    width: 42px;
    height: 42px;
  }
  
  .modal-subtitle {
    font-size: 14px;
  }
  
  .auth-links {
    flex-direction: column;
    gap: 12px;
  }
}
</style>